import axios, { AxiosRequestConfig, AxiosRequestHeaders, AxiosResponseHeaders, AxiosResponse } from 'axios';
import { Principal } from './Principal';
import { toLogin } from './KeyRoute';
import { message } from 'antd';
import { util } from './Util';
import { request } from '@@/plugin-request'



type AxiosConfigType = {
    isSilence: boolean;
    isLower: boolean;
};

function defaultRequestInterceptor(config: any) {
    return { ...config };
}

function defaultResponseInterceptor(response: any) {
    let status = response?.status;
    if (status === 401) {
        Principal.logout();
        toLogin();
    }

    return response;
}

function createHttp() {

    function getOpts() {
        let token = Principal.getToken();
        return {
            withCredentials: true,
            timeout: 30000,
            headers: {
                'Content-Type': 'application/json',
                "Authorization": `Bearer ${token}`
            },
            requestInterceptors: [defaultRequestInterceptor],
            responseInterceptors: [defaultResponseInterceptor],
        }
    }

    function post<T = any>(url: string, data: any, config: Partial<AxiosConfigType> = {}): Promise<T> {

        const finalConfig: AxiosConfigType = {
            isSilence: false,
            isLower: false,
            ...config,
        };

        let isSilence = finalConfig.isSilence;
        if (!isSilence) message.loading({ content: '加载中...', key: 'loading-post', duration: 0 });

        let opts = getOpts();

        return new Promise((resolve, reject) => {
            request(url, {
                method: 'post',
                data: data,
                ...opts
            }).then((res) => {
                if (!isSilence) message.destroy('loading-post');
                if (finalConfig.isLower && res) res = util.toLowerCaseKeys(res);
                resolve(res);
            }).catch((err) => {
                if (!isSilence) message.destroy('loading-post');
                reject(err);
            });
        });
    }

    function get<T = any>(url: string, params: any, config: Partial<AxiosConfigType> = {}): Promise<T> {
        const finalConfig: AxiosConfigType = {
            isSilence: false,
            isLower: false,
            ...config,
        };


        let isSilence = finalConfig.isSilence;
        if (!isSilence) message.loading({ content: '加载中...', key: 'loading-get', duration: 0 });

        let opts = getOpts();

        return new Promise((resolve, reject) => {
            request(url, {
                method: 'post',
                params: params,
                ...opts
            }).then((res) => {
                if (!isSilence) message.destroy('loading-get');
                if (finalConfig.isLower) res = util.toLowerCaseKeys(res);
                resolve(res);
            }).catch((err) => {
                if (!isSilence) message.destroy('loading-get');
                reject(err);
            });
        });
    }

    return { post, get };
}

export const Http = createHttp();
